<template>
  <div>
    <Row>
      <Col span="24">
        <Button @click="update">保存</Button>
      </Col>
    </Row>
    <Row>
      <Col span="9" style='margin-top:15px;margin-right:10px'>
        <Input placeholder="过滤" v-model="filterText"></Input>
        <Tree :data="treeData" ref="menuTree" show-checkbox :render="childRender"></Tree>
      </Col>
      <Col span="14" style='margin-top:15px;'>
        <Tables :columns="columns" ref="elementTable" v-model="list" :render="childRender" @on-select="handleSelectionChange" @on-select-all="handleSelectionAll"></Tables>
      </Col>
    </Row>
  </div>

</template>
<script>
import {
  removeElementAuthority,
  addElementAuthority,
  getElementAuthority,
  modifyMenuAuthority,
  getMenuAuthority,
  fetchAuthorizeTree,
  pageAuthorize
} from '@/api/admin/role/index'
import { mapGetters } from 'vuex'
import Tables from '_c/tables'
import {
  getAllChildrenIds,
  convertTree,
  getLastIds
} from '@/libs/util'
export default {
  components: {
    Tables
  },
  name: 'groupAuthority',
  props: {
    groupId: {
      default: '1'
    }
  },
  data () {
    return {
      columns: [
        { type: 'selection', width: 60, align: 'center' },
        { title: '资源类型', key: 'type' },
        { title: '资源名称', key: 'name' },
        { title: '资源地址', key: 'uri' },
        { title: '资源请求类型', key: 'method' }
      ],
      buttonProps: {
        type: 'default',
        size: 'small'
      },
      filterText: '',
      list: [],
      total: null,
      listQuery: {
        name: undefined
      },
      treeData: [],
      treeMap: {},
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      groupManager_menu: false,
      groupManager_element: false
      //   currentId: -1
    }
  },
  watch: {
    filterText (val) {
      this.$refs.menuTree.filter(val)
    }
  },
  created () {
    this.getList()
    this.groupManager_menu = this.elements['groupManager:menu']
    this.groupManager_element = this.elements['groupManager:element']
  },
  computed: {
    ...mapGetters([
      'elements'
    ])
  },
  methods: {
    getList () {
      fetchAuthorizeTree(this.listQuery).then(data => {
        const map = {
          value: 'id',
          label: 'label',
          children: 'children',
          childExpand: true
        }
        this.treeMap = {}
        this.treeData = convertTree(data, map, this.treeMap)
        this.initAuthoritys()
      })
    },
    childRender (h, { root, node, data }) {
      return h('span', {
        // style: {
        //   alignItems: 'center',
        //   justifyContent: 'space-between',
        //   fontSize: '14px',
        //   paddingRight: '8px'
        // },
        // class: {
        //   // 'ivu-tree-title-selected': node.selected === true,
        //   'ivu-tree-title': true
        // },
        on: {
          click: () => {
            // this.getTreeNodeData(data)
            // this.set(node,'selected',true)
            this.getNodeData(data)
          }
        }
      },
      [
        h('span', data.title),
        h('span', {
          style: {
            display: 'inline-block',
            float: 'right',
            marginRight: '8px'
          }
        },
        [
          h('Tooltip', {
            props: {
              content: '选中当前节点和所有下级节点',
              // placement: 'top-start',
              theme: 'dark'
            }
          },
          [
            h('Button', {
              props: Object.assign({}, this.buttonProps, {
                icon: 'ios-checkmark',
                type: 'primary',
                size: 'small'
              }),
              // style: {
              //   marginRight: '8px'
              // },
              on: {
                click: () => { this.selectChildren(data) }
              }
            })
          ]),
          h('Tooltip', {
            props: {
              content: '取消选中当前节点和所有下级节点',
              // placement: 'top-start',
              theme: 'dark'
            }
          },
          [
            h('Button', {
              props: Object.assign({}, this.buttonProps, {
                icon: 'ios-close',
                type: 'primary',
                size: 'small'
              }),
              // style: {
              //   marginRight: '8px'
              // },
              on: {
                click: () => { this.unSelectChildren(data) }
              }
            })
          ])
        ])
      ])
    },
    selectChildren (data) {
      const nodes = this.$refs.menuTree.getCheckedNodes()
      const ids = []
      ids.push(data.id)
      for (let i = 0; i < nodes.length; i++) {
        ids.push(nodes[i].id)
      }
      getAllChildrenIds(ids, data)
      ids.forEach(id => {
        this.$set(this.treeMap[id], 'checked', true)
      })
      // this.$refs.menuTree.setCheckedKeys(ids)
    },
    unSelectChildren (data) {
      const ids = []
      ids.push(data.id)
      getAllChildrenIds(ids, data)
      for (let i = 0; i < ids.length; i++) {
        this.$set(this.treeMap[ids[i]], 'checked', false)
      }
      // console.log('unSelectChildren')
    },
    filterNode (value, data) {
      if (!value) return true
      return data.label.indexOf(value) !== -1
    },
    getNodeData (data) {
      this.listQuery.menuId = data.id
      pageAuthorize(this.listQuery).then(response => {
        console.log(response)
        this.list = response.data.rows
        getElementAuthority(this.groupId).then(data => {
          const obj = {}
          for (let i = 0; i < this.list.length; i++) {
            obj[this.list[i].id] = this.list[i]
          }
          const toggle = {}
          for (let i = 0; i < data.data.length; i++) {
            const id = data.data[i]
            if (obj[id] !== undefined && toggle[id] === undefined) {
              this.$set(obj[id], '_checked', true)
              toggle[id] = true
            }
          }
        })
      })
      this.currentId = data.id
      this.showElement = true
    },
    getTreeNodeKey (node) {
      return node.id
    },
    handleSelectionChange (val, row) {
      let flag = true
      for (let i = 0; i < val.length; i++) {
        if (val[i].id === row.id) {
          addElementAuthority(this.groupId, {
            menuId: this.currentId,
            elementId: row.id
          }).then(() => {
            this.$Notice.success({
              title: '成功',
              message: '资源权限添加成功'
            })
          })
          flag = false
          break
        }
      }
      if (flag) {
        removeElementAuthority(this.groupId, {
          menuId: this.currentId,
          elementId: row.id
        }).then(() => {
          this.$Notice.success({
            title: '成功',
            desc: '资源权限移除成功'
          })
        })
      }
    },
    handleSelectionAll (val) {
      if (val.length === 0 && this.list !== null) {
        for (let i = 0; i < this.list.length; i++) {
          removeElementAuthority(this.groupId, {
            menuId: this.currentId,
            elementId: this.list[i].id
          }).then(() => {
            this.$Notice.success({
              title: '成功',
              message: '资源权限移除成功'
            })
          })
        }
      } else {
        for (let i = 0; i < val.length; i++) {
          addElementAuthority(this.groupId, {
            menuId: this.currentId,
            elementId: val[i].id
          }).then(() => {
            this.$Notice.success({
              title: '成功',
              message: '资源权限添加成功'
            })
          })
        }
      }
    },
    update () {
      this.$emit('closeAuthorityDialog')
      const nodes = this.$refs.menuTree.getCheckedNodes()
      const ids = []
      for (let i = 0; i < nodes.length; i++) {
        ids.push(nodes[i].id)
      }
      modifyMenuAuthority(this.groupId, {
        menuTrees: ids.join()
      }).then(() => {
        this.$Notice.success({
          title: '成功',
          desc: '菜单权限保存成功'
        })
      })
    },
    initAuthoritys () {
      getMenuAuthority(this.groupId).then(data => {
        let ids = []
        for (let i = 0; i < data.data.length; i++) {
          getLastIds(ids, data.data[i])
        }
        ids.forEach(id => {
          if (this.treeMap[id]) {
            this.$set(this.treeMap[id], 'checked', true)
          }
        })
      })
    }
  }
}
</script>
